package com.atomgit.ai.proxy.service.impl;

import com.atomgit.ai.proxy.entity.ModelInfo;
import com.atomgit.ai.proxy.entity.UserApiKey;
import com.atomgit.ai.proxy.mapper.ModelInfoMapper;
import com.atomgit.ai.proxy.mapper.UserApiKeyMapper;
import com.atomgit.ai.proxy.param.apikey.UserApiKeyAddParam;
import com.atomgit.ai.proxy.param.apikey.UserApiKeyDetailParam;
import com.atomgit.ai.proxy.param.apikey.UserApiKeyRemoveParam;
import com.atomgit.ai.proxy.service.UserApiKeyService;
import com.atomgit.ai.proxy.vo.UserApiKeyDetailVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserApiKeyServiceImpl implements UserApiKeyService {

    @Autowired
    private UserApiKeyMapper userApiKeyMapper;

    @Autowired
    private ModelInfoMapper modelInfoMapper;

    @Override
    public void setting(UserApiKeyAddParam param) {
        // 未自定义名称时默认为模型本来的名称
        if (param.getCustomModelName() == null || param.getCustomModelName().trim().equals("")){
            ModelInfo modelInfo = modelInfoMapper.selectById(param.getModelId());
            param.setCustomModelName(modelInfo.getName());
        }
        String versionFromParam = param.getVersion();
        String[] versionList = versionFromParam.split(",");
        for (int i = 0; i < versionList.length; i++) {
            String version = versionList[i];
            UserApiKey userApiKey = userApiKeyMapper.selectByModelIdAndVersion(param.getModelId(),version);
            if (userApiKey == null){
                userApiKey = new UserApiKey();
                BeanUtils.copyProperties(param, userApiKey);
                userApiKey.setVersion(version);
                userApiKeyMapper.insert(userApiKey);
            }
            userApiKeyMapper.updateApiKeyByModelIdAndVersion(param.getApiKey(), param.getModelId(),param.getCustomModelName());
        }
    }

    @Override
    public UserApiKeyDetailVO detail(UserApiKeyDetailParam param) {
        UserApiKey userApiKey = userApiKeyMapper.selectByModelIdAndVersion(param.getModelId(),param.getVersion());
        UserApiKeyDetailVO userApiKeyDetailVO = new UserApiKeyDetailVO();
        if (userApiKey != null){
            BeanUtils.copyProperties(userApiKey, userApiKeyDetailVO);
        }
        return userApiKeyDetailVO;
    }

    @Override
    public void remove(UserApiKeyRemoveParam param) {
        LambdaQueryWrapper<UserApiKey> wrapper = new QueryWrapper<UserApiKey>().lambda();
        wrapper.eq(UserApiKey::getModelId, param.getModelId());
        wrapper.eq(UserApiKey::getVersion, param.getVersion());
        userApiKeyMapper.delete(wrapper);
    }
}
